package servicediscovery;

public class CircuitBreaker {

    private final int FAILURE_THRESHOLD = 3;
    private final long TIMEOUT = 5000; // in milliseconds

    private int failureCount = 0;
    private long lastFailureTime = 0;
    private boolean isOpen = false;

    public void execute(Runnable command) {
        if (isOpen && (System.currentTimeMillis() - lastFailureTime) > TIMEOUT) {
            isOpen = false;
        }

        if (!isOpen) {
            try {
                command.run();
            } catch (Exception e) {
                failureCount++;
                lastFailureTime = System.currentTimeMillis();

                if (failureCount >= FAILURE_THRESHOLD) {
                    isOpen = true;
                }

                throw e;
            }
        } else {
            throw new RuntimeException("Service is unavailable");
        }
    }
}

